//
//  YLOAuthViewController.swift
//  weiBo
//
//  Created by 杨雷 on 2016/12/2.
//  Copyright © 2016年 Yang.L. All rights reserved.
//

import UIKit
import SVProgressHUD


let AppKey = "111263498"
let AppSecret = "7849fcb1a3700edf2a5401ac6b916b40"
let Redirect_uri = "http://www.qq.com"

class YLOAuthViewController: UIViewController {
    
    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavUI()
        loadRequest()
        
        
    }
    
    private func setNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(canceAction))
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    //取消
    @objc private func canceAction() {
        dismiss(animated: true, completion: nil)
    }
    
    
    //自动填充
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '4941423@qq.com'; document.getElementById('passwd').value = 'yang.4901083'")
    }
    
    
    private func loadRequest () {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    }
    

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

extension YLOAuthViewController :UIWebViewDelegate {
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //webVIew 要加载的网页url
        guard let url = request.url else {
            return false
        }
        
        //判断这个url是不是要跳转的url
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            return true
        }
        
        //获取请求的参数
        if let query = url.query, query.hasPrefix("code=") {
            //以code= 开头的是我们要截取的参数
            let startIndex = "code=".endIndex
            
            let code = query.substring(from: startIndex)
            
            YLUserAccountViewModel.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess) in
                if isSuccess {
                    print("登录成功")
                    
                    
                    self.dismiss(animated: false, completion: { 
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                    })
                } else {
                    print("登录失败")
                    
                    
                }
            })
            
            
        } else {
            dismiss(animated: true, completion: nil)
        }
        
        
        
        return false
        
    }
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}















